﻿using System;
using System.Collections.Generic;
using System.Text;
using PostSharp.Aspects.Dependencies;

namespace Arcana.Contract.Argument.Any.That.Is.Equal
{
    /// <summary>
    /// Represents a contract that adheres to <b>At least one item contained in argument is equal to</b> semantic.
    /// </summary>
    /// <remarks>
    /// <b>Note: </b>The target argument must be of type <see cref="System.Collection.IEnumerable"/>. Otherwise
    /// <see cref="System.ArgumentException"/> is thrown in validation time. <br />
    /// </remarks>
    [Serializable]
    [ProvideAspectRole(Roles.Contract)]
    [ProvideAspectRole(Roles.Method)]
    [ProvideAspectRole(Roles.Argument)]
    [ProvideAspectRole(Roles.Conditional)]
    [AspectRoleDependency(AspectDependencyAction.Commute, Roles.Conditional)]
    public sealed class ToAttribute : EnumerableComparingContractBase.ExistentialQuatification
    {
        private object _value;

        /// <summary>
        /// Initializes a new instance of <b>Argument.Any.That.Is.Equal.ToAttribute</b>.
        /// </summary>
        /// <remarks>
        /// <b>Note: </b>The target argument must be of type <see cref="System.Collection.IEnumerable"/>. Otherwise
        /// <see cref="System.ArgumentException"/> is thrown in validation time. <br />
        /// </remarks>
        /// <param name="argumentName">The argument to which this contract applies.</param>
        /// <param name="value">The value which at least one item contained in <i>argumentName</i> should be equal to.</param>
        /// <exception cref="System.ArgumentNullException"><i>argumentName</i> is <b>null</b>.</exception>
        public ToAttribute(string argumentName, object value)
            : base(argumentName)
        {
            _value = value;
        }

        /// <summary>
        /// Performs validation on an item which is stored in an argument of type <see cref="System.Collections.IEnumerable"/>.
        /// </summary>
        /// <remarks>
        /// <b>Note: </b>The target argument must be of type <see cref="System.Collection.IEnumerable"/>. Otherwise
        /// <see cref="System.ArgumentException"/> is thrown in validation time. <br />
        /// </remarks>
        /// <param name="item"></param>
        /// <returns><b>true</b> if <i>item</i> is validated, otherwise <b>false</b>.</returns>
        protected override bool ValidateItem(object item)
        {
            return Comparer.Compare(item, _value) == 0;
        }
    }
}
